package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetize.plus.entity.dto.FamilyDTO;
import com.poetize.plus.entity.po.Family;
import com.poetize.plus.entity.vo.FamilyVO;
import com.poetize.plus.entity.vo.LoveVO;
import com.poetize.plus.mapper.FamilyMapper;
import com.poetize.plus.service.FamilyService;
import com.poetize.plus.utils.TimeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Optional;

/**
 * @Author zuosy
 * @Date 2024/5/13 20:35
 **/
@Service
@RequiredArgsConstructor
public class FamilyServiceImpl extends ServiceImpl<FamilyMapper, Family> implements FamilyService {

    @Override
    public Boolean add(FamilyDTO familyDTO) {
        Long count = lambdaQuery().count();
        if (count > 0) {
            throw new IllegalArgumentException("已存在数据");
        }
        Family family = FamilyDTO.convertDTO(familyDTO);
        return baseMapper.insert(family) > 0;
    }

    @Override
    public FamilyVO info() {
        Family family = lambdaQuery().one();
        return Optional.ofNullable(family)
                .map(FamilyVO::convert)
                .orElse(null);
    }

    @Override
    public Boolean update(FamilyDTO familyDTO) {
        return baseMapper.updateById(FamilyDTO.convertDTO(familyDTO)) > 0;
    }

    @Override
    public LoveVO loveInfo() {
        Family family = lambdaQuery().one();
        return Optional.ofNullable(family)
                .map(f -> {
                    LocalDate startDate = f.getStartDate();
                    LocalDate now = LocalDate.now();

                    long years = TimeUtil.differYears(startDate, now);
                    long months = TimeUtil.differMonths(startDate, now);
                    long days = TimeUtil.differDays(startDate, now);

                    LoveVO.Time time = new LoveVO.Time(years, months, days);
                    return new LoveVO(f.getManCover(), f.getWomanCover(), f.getManName(), f.getWomanName(), time);
                }).orElse(null);
    }
}
